package com.cloudbroker.bcs.platform.ltb.common.ext.interceptor;

import com.alibaba.fastjson.JSON;
import com.cloudbroker.bcs.common.constants.BasicErrorCodes;
import com.cloudbroker.bcs.common.model.SessionIdentity;
import com.cloudbroker.bcs.common.util.VOUtil;
import com.cloudbroker.bcs.platform.ltb.bizapi.constants.HSBCPSFields;
import com.cloudbroker.bcs.platform.ltb.common.constant.type.PlatformType;
import com.cloudbroker.bcs.platform.ltb.common.util.SessionHelper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by xuyn15828 on 2016/3/26.
 */
@Component
public class AccessTokenInterceptor extends HandlerInterceptorAdapter {
    private String platform;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        Map<String, String[]> paramMap = new HashMap<>();
        paramMap = request.getParameterMap();
        if (paramMap.containsKey(HSBCPSFields.ACCESS_TOKEN)) {
            String[] accessTokenAry = paramMap.get(HSBCPSFields.ACCESS_TOKEN);
            if (accessTokenAry.length != 0) {
                String accessToken = accessTokenAry[0];
                SessionIdentity sessionIdentity = SessionHelper.getInstance().fetchSessionIdentityByAccess_token(
                        accessToken, SessionIdentity.class);
                if (sessionIdentity == null) {
                    return super.preHandle(request, response, handler);
                }
                PlatformType platformType = PlatformType.getByValue(String.valueOf(sessionIdentity.getPlatformType()));
                PlatformType currentPlatform = PlatformType.valueOf(platform.toUpperCase());
                if (!platformType.getValue().equals(currentPlatform.getValue())) {
                    OutputStream out = response.getOutputStream();
                    out.write(JSON.toJSONString(
                            VOUtil.genErrorResult(BasicErrorCodes.ACCESS_TOKEN_INVALID, "操作越权"))
                            .getBytes("UTF-8"));
                    out.flush();
                    return false;
                }
            }
        }
        return super.preHandle(request, response, handler);
    }
    
    public void setPlatform(String platform) {
        this.platform = platform;
    }
    
    public String getPlatform() {
        return platform;
    }
}
